package com.study.binds;

import com.study.annotation.bean.AppContext;
import com.study.annotation.MiniContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @author hupengming
 * @Title: 上下文解析
 * @Description:
 * @date 2022/8/30 15:56
 */
public class ContextResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        System.out.println("参数解析1");
        if(methodParameter.hasParameterAnnotation(MiniContext.class)){
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) {
        System.out.println("参数解析2");
        AppContext appContext = new AppContext();
        String uuid = (String)nativeWebRequest.getAttribute(AppContext.UUID,RequestAttributes.SCOPE_REQUEST);
        if(StringUtils.isNotEmpty(uuid)){
            appContext.setUuid(uuid);
        }
        return appContext;
    }
}
